package com.tools.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.tools.entity.Theme;
import com.tools.service.ThemeService;
import com.tools.util.Enum_ResultAttr;

@Controller
@RequestMapping("/theme")
public class ThemeAction {
    
    @Autowired
    private ThemeService themeService;
    
    @RequestMapping("/themeManage")
    public ModelAndView themeManage(HttpServletRequest request, HttpServletResponse response) {
        List<Theme> themes = themeService.getAll();
        request.setAttribute("themes", themes);
        return new ModelAndView("theme/themeManage");
        
    }
    
    /**
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/addTheme")
    public ModelAndView addTheme(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("theme/addTheme");
    }
    
    @RequestMapping("/insertTheme")
    public ModelAndView insertTheme(Theme theme, HttpServletRequest request, HttpServletResponse httpServletResponse) {
        boolean boo = themeService.insert(theme);
        Enum_ResultAttr.SAVE_STATE.setResultAttr(boo, request);
        return new ModelAndView("hint");
    }
    
    @RequestMapping("/deleteTheme")
    public void deleteTheme(@RequestParam("id") int id, HttpServletRequest request, HttpServletResponse response) {
        boolean boo = false;
        boo = themeService.delete(id);
        PrintWriter pw = null;
        try {
            String booStr = String.valueOf(boo);
            pw = response.getWriter();
            pw.print(booStr);
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @RequestMapping("/themeInfo")
    public ModelAndView themeInfo(@RequestParam("id") int id, HttpServletRequest request, HttpServletResponse response) {
        Theme theme = themeService.fetchById(id);
        request.setAttribute("theme", theme);
        return new ModelAndView("theme/updateTheme");
    }
    
    @RequestMapping("/updateTheme")
    public ModelAndView updateTheme(Theme theme, HttpServletRequest request, HttpServletResponse response) {
        boolean boo = themeService.update(theme);
        Enum_ResultAttr.UPDATE_STATE.setResultAttr(boo, request);
        return new ModelAndView("hint");
    }
}
